﻿namespace USElections.Calendar.Pages
{
    using System;
    using System.Windows;
    using Microsoft.Phone.Controls;
    using Telerik.Windows.Controls;
    using USElections.Calendar.Model;

    /// <summary>
    /// CalendarPage class.
    /// </summary>
    public partial class CalendarPage : PhoneApplicationPage
    {
        #region Fields
        private ElectionsAppointmentSource appointmentsSource = new ElectionsAppointmentSource();
        #endregion

        #region Constructor
        /// <summary>
        /// Initializes a new instance of the CalendarPage class.
        /// </summary>
        public CalendarPage()
        {
            InitializeComponent();
            this.Loaded += this.FirstLookLoaded;
        }
        #endregion

        #region Private methods
        private void FirstLookLoaded(object sender, RoutedEventArgs e)
        {
            this.DisplayAppointmentsForDate(DateTime.Now.Date);
        }

        private void RadCalendar_SelectedValueChanged(object sender, Telerik.Windows.Controls.ValueChangedEventArgs<object> e)
        {
            if (e.NewValue == null)
            {
                this.AppointmentsList.ItemsSource = null;
                return;
            }

            this.DisplayAppointmentsForDate((e.NewValue as DateTime?).Value);
        }

        private void DisplayAppointmentsForDate(DateTime date)
        {
            this.appointmentsSource.FetchData(date, date.AddDays(1));

            this.AppointmentsList.ItemsSource = this.appointmentsSource.GetAppointments((IAppointment appointment) =>
            {
                DateTime startDate = appointment.StartDate;
                DateTime endDate = appointment.EndDate;
                DateTime calendarStartDate = date.Date;
                DateTime calendarEndDate = date.AddDays(1);

                if (calendarStartDate >= startDate && calendarEndDate <= endDate)
                {
                    return true;
                }

                if (startDate >= calendarStartDate && endDate <= calendarEndDate)
                {
                    return true;
                }

                if (calendarStartDate >= startDate && calendarStartDate <= endDate)
                {
                    return true;
                }

                if (calendarEndDate >= startDate && calendarEndDate <= endDate)
                {
                    return true;
                }

                return false;
            });
        }
        #endregion
    }
}